<?php

class TaskController extends GeanyController {
    
    // <editor-fold defaultstate="collapsed" desc="STATIC & PRIVATE VARIABLE DECLARATION">
    private $validator;
    const _FUNCTION_ID = 'task';
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="CONSTRUCTOR">
  
    public function __construct(){
        parent::__construct();
        $this->loadDefaultValue();
        $this->loadServices();
        $this->validator = null;
    }
	
    // </editor-fold>
    
    // <editor-fold defaultstate="collapsed" desc="ACTION-HANDLER">
  
    public function index(){
        if (!$this->isLogin()){ return Redirect::to('login'); }
        if (!$this->isAllowAccess()){ return Redirect::to('forbidden'); }
        
        $data['Model'] = $this->mService->getList();
        return View::make('task/index', $data);
	}

    public function create(){
        if (!$this->isLogin()){ return Redirect::to('login'); }
        if (!$this->isAllowAccess()){ return Redirect::to('forbidden'); }

        $input = Input::all();
        if($input==null){
            $task = new Task();
            $task->setCreatedDate(date('d-m-y'));
            $task->setCreatedBy($this->userInformation());
            return $this->createInputView($task);
        }
        else{
            $task = $this->bindData();
            if($this->validateInput($input)==FALSE) return $this->createInputView($task);
            $this->mService->setUserInformation($this->userInformation());
            $newId = $this->mService->insertObject($task);
            if($newId!=null){
                Return Redirect::to('task/detail/'.$newId);
            }
            return $this->createInputView($task);
        }
    }
    
    public function assignTask($id=null){
        if (!$this->isLogin()){ return Redirect::to('login'); }
        if (!$this->isAllowAccess()){ return Redirect::to('forbidden'); }
        
        $input = Input::all();
        $result = $this->mService->getObject($id);
        try {
            if($result==null) {
                PageData::addModelError("Task with Id [ ".$id." ] Not Found ");
                Return Redirect::to('task')->with('ModelState',PageData::getModelState());
            }

            if($input!=null){
                $result->setTaskAssignment($this->bindDataAssignment());

                if($this->mService->assignTask($result)!=null){
                    Return Redirect::to('task/detail/'.$id);
                }
            }

            $this->data['Model'] = $result;
            if($result->getProject()!=null){
                $this->loadComboEmployee($result->getProject()->getId());
            } else {
                $this->loadComboEmployee();
            }

            return View::make('task/assign', $this->data);
        } catch (Exception $exc) {
            PageData::addModelError($exc->getMessage());
            Return Redirect::to('task');
        }
    }
    
    
    public function detail($id=null){
        if (!$this->isLogin()){ return Redirect::to('login'); }
        if (!$this->isAllowAccess()){ return Redirect::to('forbidden'); }
        
        $result = $this->mService->getObject($id);
        
        $input = Input::all();
        
        try {
            if($result==null) {
                PageData::addModelError("Task with Id [ ".$id." ] Not Found ");
                Return Redirect::to('task')->with('ModelState',PageData::getModelState());
            }
            
            if($input!=null){
                $Issue = $this->bindDataIssue();
                $IssueDao = new IssueDao();
                
                if($IssueDao->insertObject($Issue)!=null){
                    PageData::addModelError("Error Add Issue");
                    Return Redirect::to('task/detail/'.$id);
                }
            }
            
            $data['Model'] = $result;
            return View::make('task/detail', $data);
        } catch (Exception $exc) {
            PageData::addModelError($exc->getMessage());
            Return Redirect::to('task')->with('ModelState',PageData::getModelState());
        }
    }
    
    public function delete($id=null){
        if (!$this->isLogin()){ return Redirect::to('login'); }
        if (!$this->isAllowAccess()){ return Redirect::to('forbidden'); }

        try {
            $this->mService->deleteObject($id);
            
            Return Redirect::to('task');
        } catch (Exception $exc) {
            PageData::addModelError($exc->getMessage());
            Return Redirect::to('task');
        }
    }

    public function edit($id=null){
        if (!$this->isLogin()){ return Redirect::to('login'); }
        if (!$this->isAllowAccess()){ return Redirect::to('forbidden'); }
        
        $input = Input::all();
        if($input==null){
            $task = $this->mService->getObject($id);
            return $this->createInputView($task);
        }
        else{
            $task = $this->bindData();
            if($this->validateInput($input)==FALSE) return $this->createInputView($task);
            $this->mService->setUserInformation($this->userInformation());
            if($this->mService->updateObject($task,$task->getId())==true){
                Return Redirect::to('task/detail/'.$task->getId());
            }
            return $this->createInputView($task);
        }
    }

    
    public function done($id){
        if($this->mService->updateStatus("Done",$id)){
            PageData::addModelError("Error Update Status");
        }
        Return Redirect::to('task/detail/'.$id);
    }
    
    // </editor-fold>

    // <editor-fold defaultstate="collapsed" desc="PRIVATE-FUNCTION">
    
    private function loadComboProject($show_all = false){
        $arr_data = array();

        if ($show_all) $arr_data[''] = 'Pilih Nilai';
        $projectService = new ProjectService();
        $project = $projectService->getList();
        foreach ($project as $item){
            $arr_data[$item->getId()] = $item->getName();
        }
        
        $this->data['ProjectCombo'] = $arr_data;
    }
    
    private function loadComboPriority($show_all = false){
        $arr_data = array();
        
        if ($show_all) $arr_data[''] = '';
        $PriorityDao = new PriorityDao();
        $priority = $PriorityDao->getList();
        foreach ($priority as $item){
            $arr_data[$item->getId()] = $item->getName();
        }
        
        $this->data['PriorityCombo'] = $arr_data;
    }
    
    private function loadComboEmployee($projectId,$show_all = false){
        $arr_data = array();

        if ($show_all) $arr_data[''] = 'Pilih Nilai';
        $UserDao = new UserDao();
        $users = $UserDao->getListByProject($projectId);
        foreach ($users as $item){
            $arr_data[$item->getId()] = $item->getName();
        }
        
        $this->data['EmployeeCombo'] = $arr_data;
    }
    
    private function createInputView($task=null){
        $this->loadComboProject();
        $this->loadComboPriority();
        
        $this->data['Model'] = $task;
        return View::make('task/input', $this->data);
    }
    
    private function bindData(){
        $data = Input::all();
        //echo "<pre>"; var_dump($data);die();
        $task = New Task();
        $task->setId($data["id"]);
        $task->setName($data["name"]);
        $task->setStartDate(date("Y/m/d",strtotime($data["startdate"])));
        $task->setDueDate(date("Y/m/d",strtotime($data["duedate"])));
        
            $Project = new project();
            $Project->setId($data["projectid"]);
            $Project->setIsLoaded(true);
            $task->setProject($Project);

            $Status = new status();
            $Status->setId($data["statusid"]);
            $Status->setIsLoaded(true);
            $task->setStatus($Status);
            
            $Priority = new Priority();
            $Priority->setId($data["priority"]);
            $Priority->setIsLoaded(true);
            $task->setPriority($Priority);
            
        $task->setNotes($data["notes"]);

        return $task;
    }
 
    private function bindDataAssignment(){
        $data = Input::all();
        
        $taskAssignments = [];
        $taskAssignmentIds = Input::get('taskTaskAssignment', array());
        for($i=0; $i<count($taskAssignmentIds); $i++) {
            $taskAssignment = new TaskAssignment();
            $taskAssignment->setId($data["taskTaskAssignmentId"][$i]);

                $taskAssignmentTask = new task();
                $taskAssignmentTask->setId($data["taskTaskAssignmenttaskId"][$i]);
                $taskAssignmentTask->setIsLoaded(true);
                $taskAssignment->setTask($taskAssignmentTask);

                $taskAssignmentEmployee = new user();
                $taskAssignmentEmployee->setId($data["taskTaskAssignmentUserId"][$i]);
                $taskAssignmentEmployee->setIsLoaded(true);
                $taskAssignment->setUser($taskAssignmentEmployee);

            $taskAssignments[] = $taskAssignment;
        }
        
        return $taskAssignments;
    }
    
    private function bindDataIssue(){
        $data = Input::all();
        $Issue = new Issue();
        $Issue->setName($data['name']);
        $Issue->setDescription($data['name']);
        
            $task = new Task();
            $task->setId($data['task_id']);
            $task->setIsLoaded(true);
            $Issue->setTask($task);
            
            $status = new Status();
            $status->setId('open');
            $status->setIsLoaded(true);
            $Issue->setStatus($status);
            
            $priority = new Priority();
            $priority->setId('7');
            $priority->setIsLoaded(true);
            $Issue->setPriority($priority);
            
            $createdby = new User();
            $createdby->setId($this->userInformation()->getId());
            $createdby->setIsLoaded(true);
            $Issue->setCreatedBy($createdby);
            $Issue->setCreatedDate(date("Y/m/d"));
            
        $Issue->setDescription($data['name']);
        
        return $Issue;
    }
    
    private function validateInput($data){

        if($data==null) return false;
        $rules = array(
            'name' => 'required',
            'startdate' => 'date|required',
            'duedate' => 'date|required',
        );

        $this->validator = Validator::make($data, $rules);
        if($this->validator->fails()) PageData::assignValidatorToModelState ($this->validator);
        return $this->validator->passes();
    }
    
    private function loadDefaultValue(){
        $this->setFunctionId(self::_FUNCTION_ID);
        $this->page_data['_MODULE_NAME'] = $this->getFunctionName();
    }

    private function loadServices(){
        $this->mService = new TaskService();
    }
    
    // </editor-fold>
    
}
?>